package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.atguigu.tingshu.album.mapper.AlbumAttributeValueMapper;
import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.album.mapper.AlbumStatMapper;
import com.atguigu.tingshu.album.service.AlbumInfoService;
import com.atguigu.tingshu.common.cache.GuiguCache;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.album.AlbumAttributeValue;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.AlbumStat;
import com.atguigu.tingshu.query.album.AlbumInfoQuery;
import com.atguigu.tingshu.vo.album.AlbumAttributeValueVo;
import com.atguigu.tingshu.vo.album.AlbumInfoVo;
import com.atguigu.tingshu.vo.album.AlbumListVo;
import com.atguigu.tingshu.vo.album.AlbumStatVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class AlbumInfoServiceImpl extends ServiceImpl<AlbumInfoMapper, AlbumInfo> implements AlbumInfoService {

	@Autowired
	private AlbumInfoMapper albumInfoMapper;
    @Autowired
    private AlbumStatMapper albumStatMapper;
    @Autowired
    private AlbumAttributeValueMapper albumAttributeValueMapper;
    @Autowired
    private KafkaService kafkaService;




    /**
     * 根据专辑ID获取专辑统计信息
     * /api/album/albumInfo/getAlbumStatVo/{albumId}
     */
    @Override
    public AlbumStatVo getAlbumStatVo(Long albumId) {

        AlbumStatVo albumStatVo = albumStatMapper.selectAlbumStatVo(albumId);
        return albumStatVo;
    }

    @Override
    public Page<AlbumListVo> findUserAlbumPage(Page<AlbumListVo> page1, AlbumInfoQuery albumInfoQuery) {

        Page<AlbumListVo> page = albumInfoMapper.selectUserAlbumPage(page1,albumInfoQuery);

        return page;
    }

    @Override
    public void removeAlbumInfo(Long id) {
        AlbumInfo albumInfo = albumInfoMapper.selectById(id);
        if (albumInfo.getIncludeTrackCount()>0){
            throw new GuiguException(400,"请先删除音频");
        }
        albumInfoMapper.deleteById(id);
        //删除专辑统计
        LambdaQueryWrapper<AlbumStat> albumStatLambdaQueryWrapper = new LambdaQueryWrapper<>();
        albumStatLambdaQueryWrapper.eq(AlbumStat::getAlbumId,albumInfo.getId());
        albumStatMapper.delete(albumStatLambdaQueryWrapper);
        //删除专辑属性
        LambdaQueryWrapper<AlbumAttributeValue> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AlbumAttributeValue::getAlbumId,id);
        albumAttributeValueMapper.delete(lambdaQueryWrapper);

        //发送下架消息到消息队列
        kafkaService.sendMessage(KafkaConstant.QUEUE_ALBUM_LOWER,albumInfo.getId().toString());
    }

    @Override
    @GuiguCache(prefix = "albumInfo:")
    public AlbumInfo getAlbumInfo(Long id) {
        AlbumInfo albumInfo = albumInfoMapper.selectById(id);

        LambdaQueryWrapper<AlbumAttributeValue> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AlbumAttributeValue::getAlbumId, id);
        List<AlbumAttributeValue> albumAttributeValues = albumAttributeValueMapper.selectList(lambdaQueryWrapper);

        albumInfo.setAlbumAttributeValueVoList(albumAttributeValues);


        return albumInfo;
    }

    @Override
    public void updateAlbumInfo(Long id,AlbumInfoVo albumInfoVo) {

        // 创建AlbumInfo对象接收前端传递的AlbumInfoVo数据，然后用来更新album_info表
        AlbumInfo albumInfo = BeanUtil.copyProperties(albumInfoVo, AlbumInfo.class);
        albumInfo.setId(id);
        Long userId = AuthContextHolder.getUserId();
        albumInfo.setUserId(userId);

        albumInfoMapper.updateById(albumInfo);

        // 删除专辑信息和属性对应的关联表
        LambdaQueryWrapper<AlbumAttributeValue> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AlbumAttributeValue::getAlbumId,albumInfo.getId());
        albumAttributeValueMapper.delete(lambdaQueryWrapper);

        ///添加属性数据
        //保存album_attribute_value
        List<AlbumAttributeValue> albumAttributeValueVoList = albumInfo.getAlbumAttributeValueVoList();

        if (CollectionUtil.isEmpty(albumAttributeValueVoList)){
            throw new GuiguException(400,"专辑信息不完整，没有属性信息");
        }

        for (AlbumAttributeValue albumAttributeValue : albumAttributeValueVoList) {
            albumAttributeValue.setAlbumId(albumInfo.getId());
            albumAttributeValueMapper.insert(albumAttributeValue);
        }


        if ("1".equals(albumInfoVo.getIsOpen())){
            //上架
            kafkaService.sendMessage(KafkaConstant.QUEUE_ALBUM_UPPER,albumInfo.getId().toString());
        }else {
            //下架
            kafkaService.sendMessage(KafkaConstant.QUEUE_ALBUM_LOWER,albumInfo.getId().toString());
        }


    }

    /**
     * 获取当前用户全部专辑列表
     * /api/album/albumInfo/findUserAllAlbumList
     * @return
     */
    @Override
    public List<AlbumInfo> findUserAllAlbumList() {
        //LambdaQueryWrapper<AlbumInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //本地线程获取用户的id
        Long userId = AuthContextHolder.getUserId();
        //MyBatis-构建sql语句：
        QueryWrapper<AlbumInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        //根据id降序排序
        queryWrapper.orderByDesc("id");
        //过滤返回字段,只要这两列
        queryWrapper.select("id","album_title");
        //选择返回条数
        queryWrapper.last(" limit 10 ");
        List<AlbumInfo> list = albumInfoMapper.selectList(queryWrapper);
        return list;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAlbumInfo(AlbumInfoVo albumInfoVo) {
        AlbumInfo albumInfo = BeanUtil.copyProperties(albumInfoVo, AlbumInfo.class);
        Long userId = AuthContextHolder.getUserId();
        albumInfo.setUserId(userId);
        //设置免费试听集数
        albumInfo.setTracksForFree(5);
        //设置审核通过--直接审核通过--一定有后台管理员审核
        albumInfo.setStatus(SystemConstant.ALBUM_STATUS_PASS);
        //保存album_info
        albumInfoMapper.insert(albumInfo);

        List<AlbumAttributeValue> albumAttributeValueVoList = albumInfo.getAlbumAttributeValueVoList();
        if (CollectionUtil.isEmpty(albumAttributeValueVoList)){
            throw new GuiguException(400,"专辑信息不完整，没有属性信息");
        }

        for (AlbumAttributeValue albumAttributeValue : albumAttributeValueVoList) {
            albumAttributeValue.setAlbumId(albumInfo.getId());
            albumAttributeValueMapper.insert(albumAttributeValue);
        }

        //保存album_stat
        this.saveAlbumStat(albumInfo.getId(),SystemConstant.ALBUM_STAT_PLAY,0);
        this.saveAlbumStat(albumInfo.getId(),SystemConstant.ALBUM_STAT_SUBSCRIBE,0);
        this.saveAlbumStat(albumInfo.getId(),SystemConstant.ALBUM_STAT_BUY,0);
        this.saveAlbumStat(albumInfo.getId(),SystemConstant.ALBUM_STAT_COMMENT,0);

        //发送消息到消息队列
        kafkaService.sendMessage(KafkaConstant.QUEUE_ALBUM_UPPER,albumInfo.getId().toString());

    }


    private void saveAlbumStat(Long albumId, String statType, int statNum) {
        //封装统计对象
        AlbumStat albumStat = new AlbumStat();
        albumStat.setAlbumId(albumId);
        albumStat.setStatType(statType);
        albumStat.setStatNum(statNum);
        albumStatMapper.insert(albumStat);

    }
}
